const logger = require("./lib/logger");
const { spawn } = require("child_process");
const { resolve } = require("path");

logger.info("Starting GPIO logging test...");

// 启动GPIO进程
const gpioProcess = spawn(`sudo`, [
  process.execPath,
  resolve(__dirname, "./lib/gpio.js"),
]);

// 设置事件处理器
gpioProcess.stderr.on("data", (data) => {
  const errorMsg = data.toString();
  logger.error(`[GPIO Server Error] ${errorMsg}`);
});

// 添加对子进程日志消息的处理
gpioProcess.on('message', (message) => {
  if (message && message.type === 'log') {
    // 根据日志级别调用相应的日志方法
    switch (message.level) {
      case 'error':
        logger.error(`[GPIO Server] ${message.message}`);
        break;
      case 'warn':
        logger.warn(`[GPIO Server] ${message.message}`);
        break;
      case 'info':
        logger.info(`[GPIO Server] ${message.message}`);
        break;
      case 'debug':
        logger.debug(`[GPIO Server] ${message.message}`);
        break;
      default:
        logger.info(`[GPIO Server] ${message.message}`);
    }
  }
});

gpioProcess.on('exit', (code, signal) => {
  logger.warn(`[GPIO Server] 进程退出，退出码: ${code}, 信号: ${signal}`);
});

gpioProcess.on('error', (error) => {
  logger.error('[GPIO Server] 进程错误:', error.message);
});

// 发送测试命令
setTimeout(() => {
  logger.info("Sending test PWM command...");
  gpioProcess.stdin.write(`pwm 12 0.5\n`);
}, 1000);

// 关闭进程
setTimeout(() => {
  logger.info("Closing GPIO process...");
  gpioProcess.stdin.write(`exit\n`);
}, 3000);